$(function () {
    layui.use(['flow', 'form', 'layedit', 'util'], function () {
        var layer = layui.layer, form = layui.form, layedit = layui.layedit, flow = layui.flow, util = layui.util
        util.fixbar({
            click: function (type) { }
        });
        questionList(flow)
        // 加载类目
        categoryList()
        // 打开发布窗口
        $('.sendbtn').on('click', function () {
            openSend(layer, layedit, form)
        })
        // 发布问题
        $(document).on('click', '.save-question', function () {
            saveQuestion(layer)
        })
        // 技术分类按钮查询
        $('.panel-type-items').on('click', 'div', function () {
            $('#list').empty() // 先清空之前的数据再查询
            categoryId = $(this).attr('data-category-id')
            questionList(flow)
        })
        // 技术分类的【全部】按钮
        $('.tech-type span').click(function () {
            $('#list').empty() // 先清空之前的数据再查询
            categoryId = '0'
            questionList(flow)
        })
    })
})

/*
* 右边栏技术分类Id
*/
let categoryId = '0'

/**
 * 以信息流的方式加载问题列表
 * @param flow
 */
function questionList(flow) {
    // 信息流加载列表数据
    flow.load({
        elem: '#list', //指定列表容器
        isAuto: false,
        done: function (page, next) { //到达临界点（默认滚动触发），触发下一页
            let lis = [];
            let questionEntity = {pageNum: page, categoryId: categoryId}
            $.ajax({
                url: '/question/queryList',
                type: "post",
                dataType: 'json',  // 返回数据的数据类型json
                data: {questionEntity: JSON.stringify(questionEntity)},  //传送的数据
                success: function (res) {
                    layui.each(res.data, function (index, item) {
                        let img = '', subTitle = ''
                        if (item.headImgUrl != null) {
                            img = '<img src="' + item.headImgUrl + '"/>'
                        } else {
                            img = '<img src="/images/icon.png"/>'
                        }
                        if (item.subTitle != null) {
                            subTitle = item.subTitle
                        }
                        let html = '<div class="question-item layui-anim layui-anim-up">\n' +
                            '       <div class="title"><a href="/question/' + item.id + '" target="_blank">' + item.title + '</a></div>' +
                            '       <div class="info">' + subTitle + '</div>\n' +
                            '       <div class="icon-data"><div><a target="_blank" href="/user/' + item.userId + '">' + img + '</a><span><a target="_blank" href="/user/' + item.userId + '">' + item.nickName + '</a></span></div><div><span>时间：' + dateFormat(item.createTime) + ' &nbsp;&nbsp;浏览：1 分类： </span><span\n' +
                            '                            class="icon-data-type">' + item.categoryName + '</span></div></div></div>';
                        lis.push(html);
                    });
                    next(lis.join(''), page <= res.data.length);
                }
            });
        }
    });
}

/**
 * 加载类目列表
 */
function categoryList() {
    $.ajax({
        url: '/category/queryList',
        type: "POST",
        dataType: 'json',
        success: function (res) {
            layui.each(res.data, function (index, item) {
                let div = '<div data-category-id="' + item.id + '">' + item.categoryName + '</div>'
                $('.panel-type-items').append(div)
            });
        }
    });
}


/**
 * 打开发布窗口
 * @param layer
 */
function openSend(layer, layedit, form) {
    layer.open({
        shade: [0.8, '#151b2d'],
        type: 1,
        anim: 2,
        area: ['80%', '100%'],
        closeBtn: 0,
        shadeClose: true,
        offset: 'rt',
        content: $('#send-question-panel').html(),
        resize: false,
        move: false,
        title: false,
        yes: function (index, layero) {
            layer.close(index); //如果设定了yes回调，需进行手工关闭
        },
        success: function () {
            $.ajax({
                url: '/category/queryList',
                dataType: 'json',
                type: 'post',
                success: function (response) {
                    layui.each(response.data, function (index, item) {
                        let option = '<option value="' + item.id + '">' + item.categoryName + '</option>'
                        $('#categoryId').append(option)
                    })
                    form.render()
                }
            })
        }
    })
    initMarkdown(form, layer)
}

/**
 * 初始化markdown
 */
var editor

function initMarkdown(form, layer) {
    editor = editormd("test-editormd", {
        width: "100%",
        height: 700,
        path: "/editor-md/lib/",
        saveHTMLToTextarea: true,
        codeFold: true,
        toc: true,
        toolbarIcons: function () {  //自定义工具栏，后面有详细介绍
            return editormd.toolbarModes['simple']; // full, simple, mini
        },
    });
    form.render()
}

/**
 * 获取Markdown的内容
 * @param layer
 */
function saveQuestion(layer) {
    var text = editor.getMarkdown();
    var title = $.trim($('.title-content .title').val())
    var subTitle = $.trim($('#sub-title').val())
    var category = $('#categoryId').val()
    var flag = true
    if (title == null || title == '') {
        layer.tips('问题/文章标题不能为空', '.title-content .title', {tips: [3, '#202d4a']});
        flag = false;
        return;
    }
    if (text == null || text == '') {
        layer.tips('问题/文章正文不能为空', '#layui-editor', {tips: [3, '#202d4a']});
        flag = false;
        return;
    }
    if (flag) {
        $.ajax({
            url: '/question/saveQuestion',
            type: 'post',
            dataType: 'json',
            data: {title: title, content: text, subTitle: subTitle, categoryId: category},
            success: function (response) {
                if (response.code === '000000') {
                    location.reload()
                } else if (response.code === '000004') {
                    alert(response.message)
                } else if (response.code === '000403') {
                    openLogin(layer)
                }
            }
        })
    }
}